package com.example.android.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.MotionEvent
import android.view.WindowManager
import com.blankj.utilcode.util.ToastUtils
import com.example.android.databinding.DialogVoiceBinding
import com.zxf.basic.base.BottomDialog
import kotlin.properties.Delegates

/**
 * @author zjc
 * @date 2022/12/28
 */
class VoiceDialog(private val ctx: Context, private val block: VoiceDialog.(binding: DialogVoiceBinding) -> Unit) : BottomDialog<DialogVoiceBinding>(ctx, DialogVoiceBinding::inflate) {

    private lateinit var runnable: Runnable

    private var screenHeight by Delegates.notNull<Int>()
    private var contentHeight by Delegates.notNull<Int>()

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.also{ block.invoke(this, it) }
        screenHeight = ctx.resources.displayMetrics.heightPixels
        height = WindowManager.LayoutParams.MATCH_PARENT
        setCanceledOnTouchOutside(false)
        binding.apply {
            progress.setMax(100)
            runnable = Runnable {
                progress.setCurrent(progress.getCurrent() + 10)
                if (progress.getCurrent() < 100) {
                    ivVoice.postDelayed(runnable, 300)
                }
            }
            ivVoice.postDelayed(runnable, 300)
            progress.post {
                contentHeight = viewContent.measuredHeight
            }
            container.parent.requestDisallowInterceptTouchEvent(true)
            container.setOnTouchListener { _, event ->
                when (event.action) {
                    MotionEvent.ACTION_MOVE -> {
                        // +100 是为了增加灵敏度，不然手指需要往上滑很多才有效果
                        if (event.rawY < screenHeight - contentHeight + 100) {
                            tvState.text = "松开取消"
                            progress.setProgressColor(Color.parseColor("#E80F0F"))
                        } else {
                            tvState.text = "松开发送，上滑取消"
                            progress.setProgressColor(Color.parseColor("#3D42FA"))
                        }
                    }
                    MotionEvent.ACTION_UP -> {
                        if (event.rawY < screenHeight - contentHeight + 100) {
                            ToastUtils.showShort("已取消")
                        } else {
                            ToastUtils.showShort("已发送")
                        }
                    }
                }
                return@setOnTouchListener true
            }
        }
    }
}